package org.mcf.DaoImpl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.diyi.Tools.BaseDao;
import org.diyi.bean.Shoppingcar;
import org.mcf.Dao.ShoppingcarDao;

public class ShoppingcarDaoImpl extends BaseDao implements ShoppingcarDao{

	@Override
	public Integer insertCar(Shoppingcar info) {
		String sql="insert into shoppingcar(productid,userid,amount) values(?,?,?)";
		try {
			return query.update(sql,info.getProductid(),info.getUserid(),info.getAmount());
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		return -1;
	}

	@Override
	public Integer deleteCar(int id) {
		String sql="delete from shoppingcar where id=?";
		try {
			return query.update(sql,id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}

	@Override
	public List<Map<String, Object>> selectCarByid(int id) {
		String sql="select * from shoppingcar where userid=?";
		try {
			return query.query(sql, new MapListHandler(),id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> selectProinfo(int id) {
String sql="select p.*,s.userid,s.id as sid,s.amount,i.imgid as img from  product p,shoppingcar s,"
		+ "image i where p.productid=s.productid and s.userid=? and p.imgid=i.id ORDER BY s.id DESC"; 
		try {
			return query.query(sql,  new MapListHandler(),id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Integer getcount(int id) {
		String sql="select count(1) from shoppingcar where userid=?";
		 try {
			Object query2 = query.query(sql, new ScalarHandler(),id);
			return Integer.parseInt(query2.toString());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return -1;
		 
	}

	@Override
	public Integer deleteCarByoid(int userid, int oid) {
		String sql="delete   from shoppingcar where userid=? and productid in(\r\n" + 
				"select productid from orderdetail where orderid=?)";
		try {
			return query.update(sql,userid,oid);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}
	@Override
	public String showUser(int userid) {
		String sql="select username from users where userId=?";
		try {
			return (String) query.query(sql, new ScalarHandler(),userid);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
